Functions : Declaration, Expression, IIFE, Callback and More

Functions are fundamental building blocks in Node.js, used to organize code and handle logic.


1. Function Declaration

function greet(name) {
    return `Hello, ${name}!`;
}

2. Function Expression

const greet = function(name) {
    return `Hello, ${name}!`;
};

3. Arrow Function

const greet = (name) => `Hello, ${name}!`;

4. Immediately Invoked Function Expression (IIFE)

(function() {
    console.log('IIFE runs immediately!');
})();

5. Callback Functions

Functions passed as arguments.

function fetchData(callback) {
    // Simulate async operation
    setTimeout(() => {
        callback('Data received');
    }, 1000);
}

fetchData((data) => console.log(data));

6. Anonymous Functions

Functions without a name, often used as callbacks.

setTimeout(function() {
    console.log('Anonymous function');
}, 1000);

7. Rest Parameters

Collects all remaining arguments into an array.

function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

8. Default Parameters

Setting default values for function parameters.

function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

9. Higher-Order Functions

Functions that accept or return other functions.

function createMultiplier(multiplier) {
    return (x) => x * multiplier;
}
const double = createMultiplier(2);

10. Async/Await

async function fetchData() {
    const data = await fetch('url');
    console.log(data);
}

You Might Also Like

Scope

### 1. Global Scope Variables declared outside any function are in the global scope. Accessible from...

Toggle Classes Based on Conditions

Use classList.toggle to add or remove classes based on a condition. ``` const button = document.get...